package context

import (
	"go-test/src/com/miao/common/set"
	"go-test/src/com/miao/common/utils"
	"log"
	"sync"
)

type Users struct {
	sync.RWMutex
	usersmap map[string]*set.Set
}

func NewUsers()  *Users{
	return &Users{usersmap:make(map[string]*set.Set)}
}

func (users *Users) bind(chanel *ChannelContext, uid string){
	if utils.StrIsEmpty(uid) {
		log.Print("uid is not allow empty")
		return
	}
	users.Lock()
	defer users.Unlock()
	userSet := users.usersmap[uid]
	if userSet==nil {
		users.usersmap[uid]=set.New()
	}
	users.usersmap[uid].Add(chanel)
	chanel.UserId=uid
}

func (users *Users) findId(uid string)  *ChannelContext{
	return nil
}

func (users *Users) findSet(uid string)  *set.Set{
	if utils.StrIsEmpty(uid) {
		log.Print("uid is not allow empty")
		return nil
	}
	users.Lock()
	defer  users.Unlock()
	return users.usersmap[uid]
}

func (users *Users) unbind(chanel *ChannelContext, uid string){
	if utils.StrIsEmpty(uid) {
		log.Print("uid is not allow empty")
		return
	}
	if utils.StrIsEmpty(chanel.UserId) {
		log.Print(chanel.Conn.RemoteAddr().String(),"并没有绑定用户")
		return
	}
	users.Lock()
	defer users.Unlock()
	userSet :=users.usersmap[uid]
	if userSet==nil {
		log.Print(chanel.Conn.RemoteAddr().String(),"userSet不存在")
		return
	}
	chanel.UserId=""
	userSet.Remove(chanel)
	if userSet.IsEmpty() {
		delete(users.usersmap,uid)
	}
}

func (users *Users) unbindAll(chanel *ChannelContext){
	userId := chanel.UserId
	if utils.StrIsEmpty(userId) {
		return
	}
	users.unbind(chanel,userId)
}

